import sys
import random
# from serial.tools.list_ports import comports

from PySide6 import QtCore,QtWidgets,QtGui,QtSerialPort
from PySide6.QtCore import Signal,Slot,QIODevice
from PySide6.QtSerialPort import QSerialPortInfo


from ui_qtui import Ui_MyUI
# from ui_untitled import   Ui_MainWindow

class MyMainWindow(QtWidgets.QMainWindow,Ui_MyUI):

    # # 定义信号
    # signal = Signal(str)


    # 定义槽函数
    # @Slot(str)
    def connbutton_clicked(self):
        # 串口打开操作
        if(self.ComBaudenable):
            self.com.setPortName(self.ComNumber.currentText())
            self.com.setBaudRate(int(self.BaudRate.currentText()))
            if self.com.open(QIODevice.ReadWrite):
                print('Connected')
                self.ConnButton.setText('断开下位机')
            else:
                print('打开失败')

        else:
            self.com.close()
            print('disconnected')
            self.ConnButton.setText('连接下位机')

        self.ComBaudenable = not self.ComBaudenable
        self.ComNumber.setEnabled(self.ComBaudenable)
        self.BaudRate.setEnabled(self.ComBaudenable)

    def ReceDataProcess(self):
        data = self.com.readAll()
        print(data)

    def __init__(self):
        super(MyMainWindow,self).__init__()
        self.setupUi(self)

        # 串口初始化
        self.ComBaudenable = True

        self.ports = []
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.serial_com_refresh)
        self.timer.start(1000)
        self.com  = QtSerialPort.QSerialPort(self)


        # 连接信号与槽函数
        self.ConnButton.clicked.connect(self.connbutton_clicked)
        self.com.readyRead.connect(self.ReceDataProcess)

    def serial_com_refresh(self):
        current_ports = [port.portName() for port in QSerialPortInfo.availablePorts()]
        if current_ports != self.ports:
            if(set(current_ports) - set(self.ports)):
                for port in ( set(current_ports) - set(self.ports)):
                    self.ComNumber.addItem(port)
            if(set(self.ports) - set(current_ports)):
                for port in ( set(current_ports) - set(self.ports)):
                    self.ComNumber.removeItem(port.portName())
            self.ports = current_ports





if __name__ == "__main__":
    # app = QtWidgets.QApplication([])
    app = QtWidgets.QApplication(sys.argv)
    widget = MyMainWindow()
    widget.show()

    sys.exit(app.exec())
